CODE 117. Longest Common Prefix

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/11/09/2013-11-09-CODE 117 Longest Common Prefix/

访问原文「CODE 117. Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public String longestCommonPrefix(String[] strs) {
// Start typing your Java solution below
// DO NOT write main() function
if (null == strs || 0 == strs.length) {
return "";
} else if (1 == strs.length) {
return strs[0];
}
int maxIndex = strs[0].length() - 1;
if (maxIndex < 0) {
return "";
}
char[] cs = strs[0].toCharArray();
for (int i = 1; i < strs.length; i++) {
char[] ss = strs[i].toCharArray();
int j = 0;
while (j < cs.length && j < ss.length && j <= maxIndex
&& cs[j] == ss[j]) {
j++;
}
if (j > maxIndex) {
continue;
}
maxIndex = j - 1;
if (maxIndex < 0) {
return "";
}
}
return strs[0].substring(0, maxIndex + 1);
}
Jerky Lu wechat
欢迎加入微信公众号